import router from "@/router"
import { useUserStoreHook } from "@/store/modules/user"
import { ElMessage } from "element-plus"
import { setRouteChange } from "@/hooks/useRouteListener"
import { useTitle } from "@/hooks/useTitle"
import { getToken } from "@/utils/cache/cookies"
import isWhiteList from "@/config/white-list"
import NProgress from "nprogress"
import "nprogress/nprogress.css"
import { useMenuStoreHook } from "@/store/modules/menu"

const { setTitle } = useTitle()
NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, _from, next) => {
  NProgress.start()

  if (to.path === "/login") {
    return next()
  }

  const userStore = useUserStoreHook()
  const menuStore = useMenuStoreHook()
  const token = getToken()

  if (!token) {
    if (isWhiteList(to)) return next()
    return next("/login")
  }

  if (menuStore.dynamicRoute.length > 0) return next()

  try {
    await menuStore.allMenu()
    if (menuStore.code === 200) {
      return next({ ...to, replace: true })
    } else {
      return next()
    }
  } catch (err: any) {
    userStore.resetToken()
    ElMessage.error(err.message || "路由守卫过程发生错误")
    next("/login")
  }
})

router.afterEach((to) => {
  setRouteChange(to)
  setTitle(to.meta.title)
  NProgress.done()
})
